// packageH/stock/my/my.js
const App = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    checked: false,
    popupSpecs: false,
    cartList: [],

    goodsList: [],
    loading: false,
    isMoreData: true,
    page: 1,
    searchInputKeyword: "",
    searchGoodsList: null,

    stock_type: 0,
    option1: [
      { text: '全部商品', value: 0 },
      { text: '有库存商品', value: 1 },
      { text: '无库存商品', value: 2 },
    ],
    option2: [
      { text: '进行提货', value: true },
      { text: '暂不提货', value: false },
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.getGoods();
    wx.setNavigationBarTitle({
      title: '我的库存',
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getGoods();
  },
  onShareAppMessage() {},
  onShareTimeline() {},
  viewDetails(event) {
    const id = event.target.dataset.id;
    wx.navigateTo({
      url: "/packageH/stock/details/details?id=" + id,
    });
  },
  changeStockType(){
    this.data.loading = false;
    this.data.isMoreData = true;
    this.data.page = 1;
    this.data.goodsList = [];
    this.getGoods();
  },

  getGoods() {
    if (this.data.loading || this.data.isMoreData === false) {
      return;
    }
    this.setData({
      loading: true,
    });
    let urlStr = App.getNetAddresss("plugin.agency.api.stock.get-list");
    urlStr += "&page=" + this.data.page;
    urlStr += "&stock_type=" + this.data.stock_type;
    App._postNetWork({
      url: urlStr,
      success: ({ data: { data, result, msg } }) => {
        if (result === 0) {
          wx.hideLoading();
          wx.showToast({
            title: msg,
            success: () => {
              wx.redirectTo({
                url: "/packageG/member_v2/member_v2",
              });
            },
          });
          return;
        }
        const setData = {
          loading: false,
        };
        if (
          data.current_page === data.last_page ||
          data.data.length === 0 ||
          data.data.length < data.per_page
        ) {
          setData["isMoreData"] = false;
        }
        let goodsList = this.data.goodsList;
        for (let index = 0; index < data.data.length; index++) {
          data.data[index].total = 0;
        }
        goodsList.push(...data.data);
        setData["goodsList"] = goodsList;
        setData["page"] = this.data.page + 1;
        this.setData(setData);
        wx.hideLoading();
      },
    });
  },
  searchGoods(event) {
    const keyword = event.detail;
    let searchResult = this.data.goodsList.filter((item) => {
      return item.title.indexOf(keyword) !== -1;
    });
    this.setData({
      searchGoodsList: searchResult,
      searchInputKeyword: keyword,
    });
  },
  cancelSearch() {
    this.setData({
      searchGoodsList: null,
    });
  },
  onChangeSwitch({ detail }) {
    this.setData({ checked: detail });
  },
  addCart(e) {
    let _data = e.detail;
    this.activity_index = _data.index;
    if (_data.isSpecs) {
      this.activity_gid = _data.id;
      this.setData({
        goodinfo: this.data.goodsList[_data.index],
        popupSpecs: true//规格商品，显示规格弹窗
      })
      return;
    }
    this.data.cartList.push({
      goods_id: _data.id,
      total: 1,
      option_id: 0
    });
    this.setData({
      ['goodsList[' + _data.index + '].total']: 1,
      cartList: this.data.cartList
    });
  },
  changeCart(e) {
    // 更新购物车数量
    let _data = e.detail;
    
    if (_data.index !== null && _data.index !== undefined && _data.index !== ''){
      this.setData({
        ['goodsList[' + _data.index + '].total']: _data.num
      });
    };

    let _cartList = this.data.cartList;
    _cartList.forEach(element => {
      if (element.goods_id == _data.id) element.total = _data.num;
    });
    this.setData({
      cartList: _cartList,
      popupSpecs: false
    });
  },
  close_yz_specs_popup(e) {
    let found = false;
    let {clicktype,optionsId,goodsCount} = e.detail;
    if (clicktype == 1) {
      this.data.goodsList[this.activity_index].total = 0;
      this.data.cartList.forEach(element => {
        if (element.goods_id == this.activity_gid){
          if(element.option_id == optionsId) {
            found = true;
            element.total = goodsCount;
          }
          this.data.goodsList[this.activity_index].total += element.total;
        }
      });

      if (!found) {
        this.data.goodsList[this.activity_index].total += goodsCount;
        this.data.cartList.push({
          goods_id: this.activity_gid,
          total: goodsCount,
          option_id: optionsId,
        });

      }
    }
    this.setData({
      popupSpecs: false,
      goodsList: this.data.goodsList,
      cartList: this.data.cartList
    })
  },
  openCartListPopup(){
    this.data.cartList = this.data.cartList.filter(item => item.total > 0);
    if (this.data.cartList.length == 0) {
      wx.showToast({
        icon: "none",
        title: '请提货商品！',
        duration: 1000,
      });
      return;
    }

   let goods = JSON.stringify(this.data.cartList);
    wx.navigateTo({
      url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=agency-th&goods=' + goods
    });
  }
});
